package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.common.constans.user.UserConstants.AdminConstans;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.client.ArticleFeign;
import com.heima.user.client.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional

@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //判断参数
        if (dto==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //创建查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //判断status是否为空不为空就加上查询条件
        if (dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //分页查询
        Page<ApUserRealname>page =new Page<>(dto.getPage(),dto.getSize());
        IPage<ApUserRealname> realnameIPage = this.page(page, queryWrapper);
        //对查询条件进行加工
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),realnameIPage.getTotal());
        responseResult.setData(realnameIPage.getRecords());
        return responseResult;
    }

    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto) {
        //判断查询条件
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getStatus()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUserRealname realname =new ApUserRealname();
        if (dto.getStatus()== AdminConstans.FAIL_AUTH){
            if (dto.getMsg()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"请给出失败原因");

            }
            realname.setReason(dto.getMsg());

        }
        realname.setStatus(dto.getStatus());
        realname.setId(dto.getId());
       this.updateById(realname);
       createWmUserAndAuthor(realname.getId());
        System.out.println(1/0);

        return ResponseResult.okResult();
    }

    private void createWmUserAndAuthor(Integer id) {
        ApUserRealname apUserRealname = getById(id);
//        boolean flag = IdCardUtils.checkIdCardInfo(apUserRealname.getReadName(), apUserRealname.getIdno());
//        if (flag==false){
//            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"身份证与省份证号码不一致"));
//        }
        Integer userId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser==null){
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请给出失败原因"));
        }
        String name = apUser.getName();

        WmUser wmUser = wemediaFeign.findByName(name);

        if(wmUser == null){// 对应用户名的自媒体用户不存在  需要同步创建对象
            wmUser = new WmUser();

            wmUser.setApUserId(userId);
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);// 正常可用
            wmUser.setType(0);
            wmUser.setCreatedTime(new Date());
            wemediaFeign.save(wmUser); // 创建自媒体用户
        }
        // 3  查询作者信息是否存在,如果不存在,创建ApAuthor 保存
        createAuthor(wmUser);
    }
    private void createAuthor(WmUser wmUser) {
        //跟据userId查询
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findByUserId(apUserId);
        //如果为null创建作者信息
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2);
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setWmUserId(wmUser.getId());
            articleFeign.save(apAuthor);
        }
    }




}
